<template>
  <div>
    <!-- <a-button type="primary" @click="openDialog">打开弹窗</a-button> -->
    <a-row class="file-list" v-if="list.length" :gutter="[16, 0]" ref="containerRef">
      <a-col v-for="(item, index) in list" :key="item.key" style="width: 230px">
        <div class="file-item hide-scroller-bar" @click="itemClick(item, index)">
          <a-row justify="space-between" class="functional-area" :style="{
            display: item.checkedValue ? 'flex' : '',
            background: item.checkedValue ? 'rgba(0, 0, 0, 0.2)' : '',
          }">
            <a-col @click.stop>
              <a-checkbox v-if="item?.use_release !== 1" v-model:checked="item.checkedValue" @change="checkedChange" />
              <span class="use_release" v-else>已使用</span>
            </a-col>
            <a-col class="preview-menu">
              <div>
                <delete-outlined class="icon-style" @click.stop="deleteClick(item)" />
              </div>
              <div>
                <a-popover placement="right">
                  <template #content>
                    <div>
                      <a-button type="text" @click="editNameInput(item, index)">编辑名称</a-button>
                    </div>
                    <div>
                      <a-button type="text" @click="addTag(item, index)">添加标签</a-button>
                    </div>
                    <div v-if="$route.name != 'MaterialList'">
                      <a-button type="text" @click="go_DY(item, index)">发布至抖音</a-button>
                    </div>
                    <!-- <div>
												<a-button type="text" @click="cutVideoClick(item)"
												  >编辑视频</a-button
												>
											</div> -->
                    <div>
                      <a-button type="text" style="width: 90px; text-align: left"
                        @click="downloadFille(item)">下载</a-button>
                    </div>
                  </template>
                  <ellipsis-outlined @click.stop class="icon-style" style="margin-left: 5px" v-if="type !== 'text'" />
                </a-popover>
              </div>
            </a-col>
          </a-row>
          <div style="width: 100%">
            <div class="type-box">
              <!-- 文案 -->
              <div class="text-box" v-if="item.material_type == 'text'">
                <div class="text">{{ item.name }}</div>

                <div class="count_Text">
                  <a-tooltip v-if="item.usage_count" placement="top" title="素材被引用的次数">
                    <a-tag color="default" style="height:16px;line-height:16px;">{{ item.usage_count }}</a-tag>
                  </a-tooltip>
                </div>
              </div>
              <!-- 图片 -->
              <a-spin :spinning="item.spinning" tip="加载中..." v-if="item.material_type == 'image'">
                <div class="mater_box_big" v-if="item.material_type == 'image'">
                  <img v-lazy="item.thumb_url ? item.thumb_url : item.material_url" class="image"
                    @load="imageLoaded(item)" />

                  <div class="count_Text">
                    <a-tooltip v-if="item.usage_count" placement="top" title="素材被引用的次数">
                      <a-tag color="default" style="height:16px;line-height:16px;">{{ item.usage_count }}</a-tag>
                    </a-tooltip>
                  </div>
                </div>
              </a-spin>

              <!-- 视频 -->
              <a-spin :spinning="item.spinning" tip="加载中..." v-if="item.material_type == 'video'"
                style="height: 120px; width: 100%;">
                <div style="height: 120px; width: 100%; overflow: hidden;">
                  <div class="mater_box_big" style="display: flex; align-items: center; justify-content: center">
                    <img v-if="item.thumb_url" v-lazy="item.thumb_url" class="image" @load="imageLoaded(item)"
                      style="height: 120px;   object-fit: center;" />
                    <video v-else :src="item.material_url" style=" height: 100%;"
                      @loadedmetadata="loadedmetadata(item)"></video>

                    <div class="count_Text">
                      <!-- <cu-icon type="icon-ziyuanyinyong" class="count_Text_icon" /> -->
                      <!-- <span class="count_Text_wenan">{{ item.usage_count }}次</span> -->


                      <a-tooltip v-if="item.usage_count" placement="top" title="素材被引用的次数">
                        <a-tag color="default" style="height:16px;line-height:16px;">{{ item.usage_count }}</a-tag>
                      </a-tooltip>
                    </div>
                  </div>
                  <div class="duration">
                    {{ item?.material_duration_text }}
                  </div>
                </div>
              </a-spin>


              <!-- 音频 -->
              <div v-if="item.material_type == 'audio'" class="audio-box">
                <cu-icon type="icon-audio" style="font-size: 40px" />
                <div class="duration">
                  {{ item?.material_duration_text }}
                </div>

                <div class="count_Text">
                  <a-tooltip v-if="item.usage_count" placement="top" title="素材被引用的次数">
                    <a-tag color="default" style="height:16px;line-height:16px;">{{ item.usage_count }}</a-tag>
                  </a-tooltip>
                </div>
              </div>
            </div>
            <div class="title">
              <div v-if="!item.isInput">
                {{
                  item.name?.length > 12
                    ? item.name.substring(0, 12) + "..."
                    : item.name
                }}
              </div>
              <a-input v-else @click.stop v-show="item.isInput" ref="inputRefs" v-model:value="item.name"
                style="width: 100%; height: 25px; margin-top: 5px" @blur="blurChange(item)" />
            </div>
            <div style="text-align: left">{{ item.updated_at }}</div>
            <div style="text-align: left" v-if="item.bind_tags && item.bind_tags.length">
              <a-tag v-for="(item, index) in item.bind_tags" :key="index" style="margin-bottom: 5px">
                <a-tooltip zIndex="9999" v-if="item.tag?.name?.length > 10" :title="item.tag?.name">
                  <span style="cursor: pointer;">
                    {{ `${item.tag?.name.slice(0, 10)}...` }}
                  </span>
                </a-tooltip>
                <span v-else>
                  {{ item.tag?.name }}
                </span>
              </a-tag>
            </div>
          </div>
        </div>
      </a-col>
    </a-row>
    <a-empty :image="simpleImage" v-else />

    <!-- 预览图片 -->
    <PreviewModal @addTags="addThisTags" :material_item="labelInfo" :visible="visibleImage"
      @onCancel="visibleImage = false" :url="previewImgUrl" :title="previewTitle" :type="typeChange"
      :previewItem="previewItem" />

    <tagsModal :visible="tagVisible" :labelInfo="labelInfo" @close="closeTags" />
  </div>

  <!-- 导出弹框 -->
  <ExportMdal :visible="visibleExport" @cacel="visibleExport = false" />

  <!-- 预览图片 -->
  <swiperPreview :visible="swiperVisible" :coverArr="imageArr" @close="(swiperVisible = false), (imageArr = [])" />

  <!-- 删除素材被占用弹窗 -->
  <baseModel ref="dialog" @submit="onSubmit" title="删除素材" :width="920">
    <!-- <template #title>
                <span style="font-size: 15px; font-weight: 500;">确定拆分</span>
            </template> -->
    <template #content>
      <div class="titleMsg">
        已选择共计 {{ 1 }} 个素材， 其中
        <span style="color: #f0a020"> {{ 1 }} </span>
        个素材被占用
      </div>
      <div class="hint">
        <ExclamationCircleFilled style="color: #efa021" />
        以下素材已被其他业务使用，
        删除素材后可能导致使用中的业务无法正常使用，请谨慎删除
      </div>

      <div class="tableComtent">
        <a-table :rowKey="(record) => record.key" :row-selection="rowSelection" :columns="columns"
          :data-source="tableData">
        </a-table>
      </div>
    </template>
    <template #footer>
      <div style="display: flex; justify-content: space-between">
        <div style="display: flex; align-items: center">
          <a-checkbox v-model:checked="confirm"></a-checkbox>
          <span style="margin-left: 5px">我已确定素材删除的风险，依旧要删除资源（已占用{{ 0 }}个）</span>
        </div>
        <div style="">
          <a-button key="back" @click="dialog.closeModal()">取消</a-button>
          <a-button key="submit" type="primary" :disabled="!confirm" :loading="loading" @click="onSubmit"
            class="submitBtn">确定</a-button>
        </div>
      </div>
    </template>
  </baseModel>

  <!-- 详情弹框 -->
  <FileDetailModal :visible="visibleFileDetai" :data="fileData" :index="fileIndex" @addTagChange="addTag"
    @onClose="visibleFileDetai = false" @onSubmitMedia="onSubmitMedia" />
</template>

<script>
import {
  defineComponent,
  reactive,
  toRefs,
  createVNode,
  computed,
  ref,
  nextTick,
  watch,
} from "vue";
import {
  EllipsisOutlined,
  DeleteOutlined,
  ExclamationCircleFilled,
  EyeFilled,
  ExclamationCircleOutlined,
} from "@ant-design/icons-vue";

import { message, Modal, Empty } from "ant-design-vue";
import { saveAs } from "file-saver";
// 素材占用弹窗
import baseModel from "@/components/baseModel/baseModel.vue";
import PreviewModal from "../../../components/PreviewModal/index.vue";
import request from "../../../common/utils/request";
import ExportMdal from "../components/ExportMdal/index.vue";
import swiperPreview from "./swiperPreview.vue";
import tagsModal from "./modules/tagsModal.vue";
import { useRouter } from "vue-router";
import FileDetailModal from "./modules/FileDetailModal.vue";
import _ from "lodash";
export default defineComponent({
  name: "SubFileList",
  components: {
    EllipsisOutlined,
    DeleteOutlined,
    EyeFilled,
    PreviewModal,
    baseModel,
    Empty,
    ExportMdal,
    swiperPreview,
    ExclamationCircleFilled,
    ExclamationCircleOutlined,
    tagsModal,
    FileDetailModal,
  },
  emits: [
    "downloadFile",
    "fileDetail",
    "checkedChange",
    "changeSuccess",
    "refrash",
  ],
  props: {
    merchant_library_id: {
      type: String,
      default: "",
    },
    list: {
      type: Array,
      default: () => {
        return [];
      },
    },
    type: {
      type: String,
      default: "",
    },
    folderName:{
      type: String,
      default: "",
    }
  },
  setup(props, { emit }) {
    const state = reactive({
      labelInfo: {},
      count: 0,
      visibleImage: false,
      previewImgUrl: "",
      previewTitle: "",
      videoUrl: "",
      ff: {
        name: "",
        file: null,
        newName: "newVideo.mp4",
        videoUrl: "",
        newVideoUrl: "",
        blob: null,
        frames: [],
        duration: 0,
      },
      cut: {
        spliterEndTime: "00:00:08.0",
        imgs: new Array(20),
        startTime: "00:00:00.0",
        endTime: "00:00:08.0",
        show: false,
        duration: 0,
      },
      visibleExport: false,
      swiperVisible: false,
      imageArr: [],
      tagVisible: false,
      previewItem: {},

      visibleFileDetai: false,
      fileData: {},
      fileIndex: 0,
    });
    const router = useRouter();

    const dialog = ref(null);
    // 打开弹窗
    const openDialog = () => {
      dialog.value.showModal();
    };
    // 弹窗 emit
    const onSubmit = () => {
      console.log("提交");
    };
    // 确定删除勾选框
    const confirm = ref(false);
    // 弹窗内部 表格 表头数据
    const columns = [
      {
        title: "名称",
        dataIndex: "name",
        key: "name",
        // 控制合并
        customCell: (record) => {
          // 这里可以返回一个对象，该对象包含了这个单元格特定的属性
          return {
            rowSpan: record.rowSpan,
          };
        },
        render: (text, record, index) => {
          // 在这里实现你的自定义渲染逻辑
          // 例如，通过某种逻辑判断是否渲染选择框，或者是一个代表已选择的图标等
        },
      },
      {
        title: "关联对象类型",
        dataIndex: "objType",
        key: "objType",
      },
      {
        title: "关联对象",
        dataIndex: "objName",
        key: "objName",
      },
      {
        title: "关联对象状态",
        key: "objState",
        dataIndex: "objState",
      },
    ];

    // 模拟数据
    const tableData = [
      {
        name: "1122.mp4",
        objType: "关联类型2",
        objName: "视频集合2",
        objState: "已剪辑",
        key: 2,
      },
      {
        name: "7788.mp4",
        objType: "关联类型3",
        objName: "视频集合3",
        objState: "未剪辑",
        key: 3,
      },
    ];

    const rowSelection = ref({
      type: "checkbox", // 使用复选框
    });

    const checkedChange = () => {
      emit("checkedChange");
    };

    const inputRefs = ref([]);
    const editNameInput = (item, index) => {
      nextTick(() => {
        setTimeout(() => {
          inputRefs.value[index].focus();
        }, 5);
      });
      item.isInput = true;
    };

    const downloadFille = (data) => {
      if (data?.image_ary && data?.image_ary?.length) {
        state.visibleExport = true;
        request
          .put("/work_ai", "/user/shotstack/media/image_text/download", {
            id: data?.id,
          })
          .then((res) => {
            console.log("res===>", res);
          })
          .catch((err) => {
            console.log("err===>", err);
          });
        return;
      }
      try {
        const hide = message.loading("下载中..", 0);
        saveAs(data.material_url, data.name);
        data.soundLoading = false;
        setTimeout(hide, 0);
      } catch (error) {
        data.soundLoading = false;
        message.error("下载失败");
        return;
      }
    };

    // 编辑视频
    const cutVideoClick = (data) => {
      console.log(data);
    };

    // 删除确定
    const deleteClick = (item) => {
      Modal.confirm({
        title: `确定删除该素材吗？`,
        icon: createVNode(ExclamationCircleOutlined),
        cancelText: "取消",
        okText: "确定",
        onOk() {
          if (props.type == "text") {
            request
              .del("/work_ai", "/user/shotstack/text", {
                mediaIds: item.id,
              })
              .then((res) => {
                message.success("删除成功");
                emit("changeSuccess");
              });
          } else {
            request
              .del("/work_ai", "/user/shotstack/media", {
                mediaIds: [item.id],
              })
              .then((res) => {
                message.success("删除成功");
                emit("changeSuccess");
              });
          }
        },
      });
    };

    const blurChange = (item) => {
      if (!item.name) {
        message.warn("请输入名称");
        return;
      }
      if (item.name.length > 20) {
        message.error("素材名称不能超过20个字符");
        return;
      }
      let params = {
        id: item.id,
        material_name: item.name,
      };

      request
        .put("/work_ai", "/user/shotstack/media/name", params)
        .then((res) => {
          message.success("修改成功");
          item.isInput = false;
          emit("changeSuccess");
        });
    };

    //文件预览
    const previewImg = (item, index) => {
      // debugger
      state.previewItem = item;
      if (props.type == "text") {
        state.previewTitle = "文案预览";
      } else {
        state.previewTitle = item.material_name;
      }
      // if (item?.image_ary && item?.image_ary?.length) {
      // 	state.swiperVisible = true
      // 	state.imageArr = item.image_ary
      // 	return
      // }
      state.previewImgUrl = item.material_content || item.material_url;
      state.visibleImage = true;
      // 文本标签小弹窗需要的信息
      state.labelInfo = item;
      state.labelInfo.index = index;
    };

    const typeChange = computed(() => {
      return props.type;
    });

    // 添加标签
    const addTag = (item, index) => {
      state.tagVisible = true;
      state.labelInfo = item;
      state.labelInfo.index = index;
    };

    const addThisTags = () => {
      state.tagVisible = true;
    };

    const closeTags = (flag) => {
      state.tagVisible = false;
      if (flag) {
        emit("refrash", "tagSubmit");
      }
    };

    // 发布至抖音
    const go_DY = (item, index) => {
      //  const labelInfoStr = JSON.stringify(item);
      router.push({
        name: "AutoRelease",
        query: {
          choose: "1",
          id: item.id,
          // labelInfo: labelInfoStr,
          merchant_library_id: props.merchant_library_id,
          material_type: item.material_type,
          // 进入发布页的类型为 素材库
          // openType:'material'
        },
      });
    };

    const itemClick = (item, index) => {
      if (item.material_type == "text") {
        previewImg(item);
        return;
      }
      item.folderName = props.folderName
      state.fileData = item;
      state.fileIndex = index;
      state.visibleFileDetai = true;
    };

    const imageLoaded = (item) => {
      item.spinning = false;
    };

    const loadedmetadata = (item) => {
      item.spinning = false;
    };

    // 识别字幕成功
    const onSubmitMedia=()=>{
      state.visibleFileDetai = false;
      emit('changeSuccess')
    }

    // 状态颜色
    const statusColor=(status)=>{
      let color = " ";
      switch (status) {
        case '0':
          color = "orange";
          break;
        case '1':
          color = "green";
          break;
        case '2':
          color = "red";
          break;
      }
      return color;
    };

    const statusText=(status)=>{
      let color = "";
      switch (status) {
        case '0':
          color = "待执行";
          break;
        case '1':
          color = "执行成功";
          break;
        case '2':
          color = "执行失败";
          break;
      }
      return color;
    };

    watch(
      () => props.list,
      (val) => {
        if (val && val?.length) {
          if (state.labelInfo?.index || state.labelInfo?.index == 0) {
            state.labelInfo = val[state.labelInfo?.index];
          }
        }
      },
      {
        deep: true,
        immediate: true,
      }
    );
    // 重新转码
    const RetransCode = _.debounce((info) => {
      request
        .put("/work_ai", "/user/shotstack/media/conversion", {
          multimedia_id: info?.id,
        })
        .then((res) => {
          console.log("res===>", res);
          emit("refrash"); //刷新素材列表
        })
        .catch((err) => {
          console.log("err===>", err);
        });
    }, 800);

    return {
      ...toRefs(state),
      go_DY,
      checkedChange,
      editNameInput,
      downloadFille,
      deleteClick,
      previewImg,
      typeChange,
      blurChange,
      cutVideoClick,
      onSubmit,
      addTag,
      openDialog,
      simpleImage: Empty.PRESENTED_IMAGE_SIMPLE,
      inputRefs,
      dialog,
      columns,
      tableData,
      closeTags,
      addThisTags,
      // table
      rowSelection,
      confirm,
      itemClick,
      imageLoaded,
      loadedmetadata,
      RetransCode,
      onSubmitMedia,
      statusColor,
      statusText
    };
  },
});
</script>
<style lang="less">
video:focus {
  outline: -webkit-focus-ring-color auto 0px;
}

:deep(.ss-spin-text) {
  text-shadow: none !important;
  color: red;
}
</style>
<style lang="less" scoped>
.text-limit {
  display: -webkit-box;
  /* Safari */
  -webkit-line-clamp: 2;
  /* number of lines to show */
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.file-list {
  margin-top: 10px;
  display: flex;
  flex-wrap: wrap;
  overflow: auto;

  .file-item {
    border-radius: 5px;
    margin-right: 10px;
    margin-bottom: 10px;
    padding-bottom: 5px;
    display: flex;
    flex-direction: column;
    align-items: center;
    text-align: center;
    position: relative;
    cursor: pointer;

    .use_release {
      color: red;
      background: #d0d0d0;
      border-radius: 5px;
      padding: 2px 4px;
      font-weight: 500;
    }

    .badge {
      position: absolute;
      top: 25px;
      right: 25px;

      background: rgba(0, 0, 0, 0.2);
      border-radius: 50%;
      color: #fff;
    }

    .icon-postion {
      position: absolute;
      top: 45px;
      left: 50px;
      font-size: 22px;
      cursor: pointer;
    }

    .functional-area {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      padding: 5px;
      z-index: 10;
      align-items: center;

      .preview-menu {
        // width: 45px;
        padding: 2px;
        height: 16px;
        margin-top: 2px;
        display: flex;
        align-items: center;
        justify-content: space-around;
        color: #d0d0d0;

        .icon-style {
          cursor: pointer;
          padding-left: 1.5px;
          font-size: 16px;
          color: #fff;

          &:hover {
            color: #ff807e;
          }
        }
      }

      display: none;
    }

    &:hover {
      .functional-area {
        display: flex;
        background: rgba(0, 0, 0, 0.2);
        border-top-right-radius: 8px;
        border-top-left-radius: 8px;
      }
    }

    .image-box {
      margin-top: 40px;
      width: 100%;
      text-align: center;

      .image {
        width: 70px;
        height: 70px;
        border-radius: 4px;
        margin: 0 auto;
        position: relative;

        .image-mask {
          position: absolute;
          top: 0px;
          left: 0px;
          width: 70px;
          height: 70px;
          border-radius: 4px;
          background: rgba(0, 0, 0, 0.1);
          display: flex;
          align-items: center;
          justify-content: center;
          cursor: pointer;
          opacity: 0;
          color: #fff;

          .icon-eye-filled {
            font-size: 24px;

            &:hover {
              color: #2878ff;
            }
          }
        }

        &:hover {
          .image-mask {
            opacity: 1;
          }
        }

        .durationText {
          position: absolute;
          left: 2px;
          bottom: 0px;
          color: #fff;
        }
      }

      .image-name {
        padding: 0 6px;
        height: 50px;
        padding-top: 5px;
        word-wrap: break-word;
      }

      .image-time {
        font-size: 12px;
        color: #9ea4aa;
      }
    }

    .title {
      text-align: left;
      font-weight: 700;
      margin-top: 5px;
    }

    .type-box {
      width: 100%;
      height: 120px;
      position: relative;
      background-color: #000;
      border-radius: 10px;

      :deep(.ss-spin-nested-loading > div > .ss-spin .ss-spin-text) {
        text-shadow: none;
      }

      .text-box {
        width: 100%;
        height: 100%;

        color: #fff;
        background: rgba(0, 0, 0, 0.6);
        border-radius: 5px;
        padding: 20px;

        display: flex;
        justify-content: center;
        align-items: center;
        position: relative;

        .count_Text {
          position: absolute;
          left: 8px;
          bottom: 5px;
          z-index: 9999 !important;

          .count_Text_icon {
            font-size: 20px;
            color: #fff;
            margin-right: 3px;
          }

          .count_Text_wenan {
            color: #fff;
          }
        }

        .text {
          display: -webkit-box;
          -webkit-line-clamp: 4;
          -webkit-box-orient: vertical;
          overflow: hidden;
          text-overflow: ellipsis;


        }
      }

      .image {
        // width: 100%;
        height: 100%;
        object-fit: contain;
        // border-radius: 5px;
      }

      .video-box {
        width: 100%;
        height: 120px;
        border-radius: 5px;
      }

      .duration {
        position: absolute;
        bottom: 5px;
        right: 5px;
        padding: 0 5px;
        border-radius: 5px;
        background: rgba(0, 0, 0, 0.3);
        color: #fff;
      }

      .status_text{
        position: absolute;
        bottom: 5px;
        left: 5px;
      }

      .status {
        position: absolute;
        bottom: 5px;
        left: 5px;
        padding: 0 5px;
        border-radius: 5px;
        // background: rgba(0, 0, 0, 0.3);
        color: #fff;
      }

      .status_active {
        &:hover {
          color: var(--ss-primary-color);
        }
      }

      .audio-box {
        height: 100%;
        color: #fff;
        background: rgba(0, 0, 0, 0.6);
        border-radius: 5px;
        display: flex;
        justify-content: center;
        align-items: center;

        .count_Text {
          position: absolute;
          left: 8px;
          bottom: 5px;

          .count_Text_icon {
            font-size: 20px;
            color: #fff;
            margin-right: 3px;
          }

          .count_Text_wenan {
            color: #fff;
          }
        }
      }
    }
  }
}

.titleMsg {
  margin-bottom: 10px;
}

.hint {
  background-color: #fce9cc;
  padding: 6px 4px;
  margin-bottom: 15px;
}

.icon {
  font-size: 70px;
  cursor: pointer;
  color: #fff;
  font-size: 45px;
}


.mater_box_big {
  position: relative;
  // width: 100%;
  border-radius: 5px;
  height: 120px;
  overflow: hidden;

  .count_Text {
    position: absolute;
    left: 8px;
    bottom: 5px;

    .count_Text_icon {
      font-size: 20px;
      color: #fff;
      margin-right: 3px;
    }

    .count_Text_wenan {
      color: #fff;
    }
  }
}
</style>
